#!/usr/bin/env python3
"""
DataPlexus 数据源管理功能完整初始化脚本
一键完成数据库表创建、权限初始化、路由配置等所有设置
"""

import sys
import os
import asyncio
import subprocess
from datetime import datetime

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app.core.logger import logger
from init_datasource_permissions import DataSourcePermissionInitializer
from add_datasource_route import DataSourceRouteInitializer


class DataSourceManagementSetup:
    """数据源管理功能设置器"""
    
    def __init__(self):
        self.script_dir = os.path.dirname(os.path.abspath(__file__))
        self.project_root = os.path.dirname(self.script_dir)
    
    def execute_sql_script(self, sql_file_path: str) -> bool:
        """执行SQL脚本"""
        try:
            logger.info(f"执行SQL脚本: {sql_file_path}")
            
            # 从配置中获取数据库连接信息
            from app.core.config import settings
            
            # 构建MySQL命令
            mysql_cmd = [
                'mysql',
                '-h', settings.DB_HOST,
                '-P', str(settings.DB_PORT),
                '-u', settings.DB_USER,
                f'-p{settings.DB_PASSWORD}',
                settings.DB_NAME
            ]
            
            # 执行SQL脚本
            with open(sql_file_path, 'r', encoding='utf-8') as sql_file:
                result = subprocess.run(
                    mysql_cmd,
                    stdin=sql_file,
                    capture_output=True,
                    text=True,
                    timeout=300  # 5分钟超时
                )
            
            if result.returncode == 0:
                logger.info(f"SQL脚本执行成功: {sql_file_path}")
                if result.stdout:
                    logger.info(f"输出: {result.stdout}")
                return True
            else:
                logger.error(f"SQL脚本执行失败: {sql_file_path}")
                logger.error(f"错误: {result.stderr}")
                return False
                
        except subprocess.TimeoutExpired:
            logger.error(f"SQL脚本执行超时: {sql_file_path}")
            return False
        except FileNotFoundError:
            logger.error("MySQL客户端未找到，请确保MySQL已安装并在PATH中")
            return False
        except Exception as e:
            logger.error(f"执行SQL脚本时发生错误: {str(e)}")
            return False
    
    async def setup_database_tables(self) -> bool:
        """设置数据库表"""
        logger.info("开始创建数据源管理相关数据库表...")
        
        sql_file = os.path.join(self.script_dir, 'create_datasource_tables.sql')
        
        if not os.path.exists(sql_file):
            logger.error(f"SQL脚本文件不存在: {sql_file}")
            return False
        
        success = self.execute_sql_script(sql_file)
        
        if success:
            logger.info("数据库表创建完成")
        else:
            logger.error("数据库表创建失败")
        
        return success
    
    async def setup_permissions(self) -> bool:
        """设置权限"""
        logger.info("开始初始化数据源管理权限...")
        
        try:
            initializer = DataSourcePermissionInitializer()
            result = await initializer.run()
            
            logger.info("权限初始化完成")
            logger.info(f"创建权限: {result['permissions']['created']}")
            logger.info(f"更新权限: {result['permissions']['updated']}")
            logger.info(f"分配权限: {result['assignments']['assigned']}")
            
            return True
            
        except Exception as e:
            logger.error(f"权限初始化失败: {str(e)}")
            return False
    
    async def setup_routes(self) -> bool:
        """设置路由"""
        logger.info("开始初始化数据源管理路由...")
        
        try:
            initializer = DataSourceRouteInitializer()
            result = await initializer.run()
            
            logger.info("路由初始化完成")
            logger.info(f"路由操作: {result['route']['action']}")
            logger.info(f"路由路径: {result['route']['route_path']}")
            logger.info(f"分配权限: {result['permissions']['assigned']}")
            
            return True
            
        except Exception as e:
            logger.error(f"路由初始化失败: {str(e)}")
            return False
    
    def check_dependencies(self) -> bool:
        """检查依赖项"""
        logger.info("检查依赖项...")
        
        # 检查MySQL客户端
        try:
            result = subprocess.run(['mysql', '--version'], capture_output=True, text=True)
            if result.returncode == 0:
                logger.info(f"MySQL客户端版本: {result.stdout.strip()}")
            else:
                logger.error("MySQL客户端不可用")
                return False
        except FileNotFoundError:
            logger.error("MySQL客户端未安装")
            return False
        
        # 检查Python依赖
        required_modules = ['cryptography', 'aiomysql', 'asyncpg', 'cx_Oracle', 'pyodbc']
        missing_modules = []
        
        for module in required_modules:
            try:
                __import__(module)
                logger.info(f"模块 {module} 已安装")
            except ImportError:
                missing_modules.append(module)
                logger.warning(f"模块 {module} 未安装")
        
        if missing_modules:
            logger.warning(f"以下模块未安装，可能影响某些数据库类型的连接: {', '.join(missing_modules)}")
            logger.info("可以使用以下命令安装:")
            logger.info(f"pip install {' '.join(missing_modules)}")
        
        return True
    
    async def run_setup(self) -> bool:
        """运行完整设置"""
        logger.info("开始DataPlexus数据源管理功能初始化...")
        
        start_time = datetime.now()
        
        try:
            # 检查依赖项
            if not self.check_dependencies():
                logger.error("依赖项检查失败")
                return False
            
            # 创建数据库表
            if not await self.setup_database_tables():
                logger.error("数据库表创建失败")
                return False
            
            # 初始化权限
            if not await self.setup_permissions():
                logger.error("权限初始化失败")
                return False
            
            # 初始化路由
            if not await self.setup_routes():
                logger.error("路由初始化失败")
                return False
            
            end_time = datetime.now()
            duration = (end_time - start_time).total_seconds()
            
            logger.info(f"数据源管理功能初始化完成！耗时: {duration:.2f}秒")
            
            return True
            
        except Exception as e:
            logger.error(f"初始化过程中发生错误: {str(e)}")
            return False
    
    def print_next_steps(self):
        """打印后续步骤"""
        print("\n" + "="*80)
        print("🎉 DataPlexus 数据源管理功能初始化完成！")
        print("="*80)
        print("\n📋 后续步骤:")
        print("1. 重启后端服务:")
        print("   cd backend && python -m uvicorn app.main:app --reload")
        print("\n2. 重启前端服务:")
        print("   cd frontend && npm start")
        print("\n3. 访问数据源管理页面:")
        print("   http://localhost:3000/datasources")
        print("\n4. 设置环境变量（可选）:")
        print("   export DATASOURCE_ENCRYPTION_KEY=your-secret-key-here")
        print("\n5. 安装额外数据库驱动（可选）:")
        print("   pip install cx_Oracle pyodbc  # Oracle和SQL Server支持")
        print("\n" + "="*80)


async def main():
    """主函数"""
    try:
        setup = DataSourceManagementSetup()
        success = await setup.run_setup()
        
        if success:
            setup.print_next_steps()
            return True
        else:
            print("\n❌ 数据源管理功能初始化失败")
            print("请检查日志获取详细错误信息")
            return False
            
    except KeyboardInterrupt:
        print("\n⚠️ 初始化被用户中断")
        return False
    except Exception as e:
        print(f"\n❌ 初始化失败: {str(e)}")
        return False


if __name__ == "__main__":
    success = asyncio.run(main())
    sys.exit(0 if success else 1)
